const router = require('express').Router()
const multiparty = require('multiparty')
const mysqlhandle = require('../routehandles/mysqlhandle')
const path = require('path')
const fs = require('fs')
var AipImageClassifyClient = require("baidu-aip-sdk").imageClassify;
var HttpClient = require("baidu-aip-sdk").HttpClient;
const { resolve } = require('path')
var exec = require("child_process").exec;

var APP_ID = "26570191";  //图像识别 APP_ID
var API_KEY = "nGr1nYvSM37QOmuuiFdM6HwT";  //图像识别 API_KEY
var SECRET_KEY = "NmpXfiwpEHbw71NUVH53MwEKd8HPbGhe"; //图像识别 SECRET_KEY

const multer = require("multer"); //导入multer模块
const upload = multer({ dest: "tmp/" });

router.post("/upload", upload.single("file"),async function (req, res) {
    var params = req.body
    var username = getUsername(req.url)  //获取前端传来的username
    var tasknum = getTasknum(req.url) //获取前端传来的tasknum
    var order = getSerial(req.url) //获取前端传来的tasknum
    var publishtable =  await mysqlhandle.sPublishTableById(tasknum) //根据tasknum查询PublishTable
    var pushtable =  await mysqlhandle.sPushTableBytasknum(tasknum)
    var tag = publishtable[0]['tag'] //tag存储任务的标签
    var floderpath = publishtable[0]['picurl']  //获取任务图片文件夹路径
    console.log("floderpath")
    console.log(floderpath)
    console.log("length")
    console.log(pushtable.length)
    //var picpath = path.join(floderpath,"./"+pushtable.length+".jpg")  //图片路径

    let imgFile = req.file; //获取图片上传的资源
    var tmp = imgFile.path; //获取临时资源
    let fileData = await fs.readFileSync(tmp); //将上传到服务器上的临时资源 读取到 一个变量里面
    // let ext = path.extname(imgFile.originalname); //利用path模块获取 用户上传图片的 后缀名
    // let newName = "xxx.jpg" //给用户上传的图片重新命名 防止重名
    // let newPath = "/public/picture/" + newName; //给图片设置存放目录  提前给当前文件夹下建立一个   images文件夹  ！！！！
    let filePath = path.join(floderpath, "./"+pushtable.length+".jpg");
    await fs.writeFileSync(filePath, fileData); //重新书写图片文件  写入到指定的文件夹下
    var isExist = await pictureClassfication(filePath,"猫")
    console.log("isExist:")
    console.log(isExist)
    if(isExist){
        filePath = filePath.replace(/\\/g,'/')
        // var pics = "http://localhost"+filePath.substr(filePath.indexOf("/picture"))
        mysqlhandle.iPushTable(username,tasknum,filePath,"已提交")
        var userinfo = await mysqlhandle.sUAPTable(username)
        var balance = parseFloat(userinfo[0]["balance"]) //获取发布者余额
        mysqlhandle.uUAPTable("balance",(balance*10+2)/10,username)//修改发布任务者的余额
        res.json({msg:"成功",serial:order})
    }
    else{
        fs.unlink(filePath,(err) => {
            if(err){
                console.log(err);
            }
        })
        res.json({msg:"失败",serial:order})
    }
    // res.send(newPath); //上传成功之后  给客户端响应
  });
  
router.get('/public/images/*', function (req, res) {
    let newPath = ".."+req.url;
    let filePath = path.join(__dirname,newPath);
    res.sendFile(filePath);
})

//处理上传图片请求
router.post('/uppicture',  async function(req,res){
    const params = req.body
    var username = getUsername(req.url)  //获取前端传来的username
    var tasknum = getTasknum(req.url) //获取前端传来的tasknum
    var order = getSerial(req.url) //获取前端传来的tasknum
    console.log("rwh:"+tasknum)
    var publishtable =  await mysqlhandle.sPublishTableById(tasknum) //根据tasknum查询PublishTable
    var pushtable =  await mysqlhandle.sPushTableBytasknum(tasknum)
    console.log(publishtable)
    console.log(pushtable)
    //var tag = '象'
    var tag = publishtable[0]['tag'] //tag存储任务的标签
    //var floderpath = path.join(__dirname,'../public/picture') //floderpath存储图片的文件夹路径
    var floderpath = publishtable[0]['picurl']  //获取任务图片文件夹路径
    //var order = String(params.serial)
    var picpath = path.join(floderpath,"./"+pushtable.length+".jpg")  //图片路径
    //var picc = "/picture/4.jpg"
    //var xxx = new Promise((resolve,reject) => storePic(req,floderpath,picpath)).then(await pictureClassfication(picpath,tag))
    //storePic(req,floderpath,picpath)
    let form = new multiparty.Form({
        uploadDir: floderpath
    })
    form.parse(req, (err, fields, files) => {
        console.log("上传成功")
        console.log("标签："+tag)
        //更改图片名
        fs.rename(files.file[0].path,picpath,async function(err){
            if(err){
                throw err;
            }
            var isExist = await pictureClassfication(picpath,tag)
            if(isExist){
                picpath = picpath.replace(/\\/g,'/')
                var pics = "http://localhost"+picpath.substr(picpath.indexOf("/picture"))
                mysqlhandle.iPushTable(username,tasknum,pics,"已提交")
                var userinfo = await mysqlhandle.sUAPTable(username)
                var balance = parseFloat(userinfo[0]["balance"]) //获取发布者余额
                mysqlhandle.uUAPTable("balance",(balance*10+2)/10,username)//修改发布任务者的余额
                res.json({msg:"成功",serial:order})
            }
            else{
                fs.unlink(picpath,(err) => {
                    if(err){
                        throw err;
                    }
                })
                res.json({msg:"失败",serial:order})
            }
            console.log("是否存在？"+isExist)
        })
    })
})
  
//获取url传递的参数
function getUsername(url){
    var result;
    var url=decodeURI(url); //获取url中"?"符后的字串  
    if(url.indexOf("?") != -1) {
        result = url.substr(url.indexOf("username=")+9,11);
    }
    return result;
}
function getTasknum(url){
    var result;
    var url=decodeURI(url); //获取url中"?"符后的字串  
    if(url.indexOf("?") != -1) {
        result = url.substr(url.indexOf("tasknum=")+8,url.indexOf("serial=")-url.indexOf("tasknum=")-9);
    }
    return result;
}
function getSerial(url){
    var result;
    var url=decodeURI(url); //获取url中"?"符后的字串  
    if(url.indexOf("?") != -1) {
        result = url.substr(url.indexOf("serial=")+7);
    }
    return result;
}


//图像识别函数
function pictureClassfication(picture,taskTag){
    //var isExist = false
    // 新建一个对象，建议只保存一个对象调用服务接口
    var client = new AipImageClassifyClient(APP_ID, API_KEY, SECRET_KEY);

    HttpClient.setRequestOptions({timeout: 5000});
    HttpClient.setRequestInterceptor(function(requestOptions) {
        // 查看参数
        // console.log(requestOptions)
        // 修改参数
        requestOptions.timeout = 5000;
        // 返回参数
        return requestOptions;
    })
    var image = fs.readFileSync(picture).toString("base64")
    // 如果有可选参数
    var options = {};
    options["baike_num"] = "5";
    // 带参数调用通用物体识别
    var maybeResult =[]  //maybeResult存储识别后可能的keyword值
    var maybeScore = []  //maybeScore存储对应结果的score值
    return client.advancedGeneral(image, options).then(function(result) {
        for(var i=0; i<5; i++){
            maybeResult.push(result['result'][i].keyword)
            maybeScore.push(result['result'][i].score)
        }
        console.log("可能情况：")
        console.log(maybeResult);
        console.log(maybeScore)
        //判断可能的结果中有没有符合tag的结果
        for(var i=0; i<5; i++){
            if(String(maybeResult[i]).indexOf(taskTag) != -1) {
                if(maybeScore[i]>0.1){
                    console.log(maybeResult[i]+maybeScore[i])
                    return true
                }
            }
        }
        return false
    }).catch(function(err) {
        // 如果发生网络错误
        console.log(err);
        return false
    });;
    // console.log("isExist2:"+isExist)
    // return isExist
}


const child_process = require('child_process')
//const py = spawn('python3', ['D:/Study/pythonProject/similarity.py'])
//const jsexecpy = require("jsexecpy")
const spawn = require('child_process').spawn
// app.get("process_data", (req, res) => {
//     spawn('python3', ['../../../pythonProject/similarity.py'])
// })

router.post('/testup',(req,res) => {
    console.log("testup")
    similar()
    //let stdout = child_process.execSync('python3 ../../../pythonProject/similarity.py',{encoding:'utf-8'})
    //console.log("stdout"+stdout)
    res.json({msg:'python'})
})

function similar(){
    var data = {
        img1:'C:/Users/86188/Pictures/Camera Roll/m6.png',
        img2:'C:/Users/86188/Pictures/Camera Roll/m7.png',
    }
    const py = spawn('python', ['../../../pythonProject/similarity.py'])
    py.stdin.write(JSON.stringify(data)) //we have to send data as a string, so we are using JSON.stringify
    py.stdin.end()
    var data = ""
    py.stdout.on('data', function(res){
       data = JSON.parse(res.toString())
       console.log("python结果:")
       console.log(data)
    })
    console.log("这")
    return data
}

router.post('/download',async (req,res) => {
    var params = req.body
    var xx = await mysqlhandle.sPushTableBytasknum(params.tasknum)
    res.json(xx)
})
module.exports = router